package cn.zcy.springboot_web.interceptors;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 记录当前请求的执行时间的拦截器
 */
public class TimeInterceptors implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(TimeInterceptors.class);
    LocalDateTime begin;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //开始时间
         begin = LocalDateTime.now();
        logger.info("当前请求"+request.getRequestURI()+"开始时间为=" + begin+"毫秒");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //结束时间
        LocalDateTime end = LocalDateTime.now();
        //计算时间差
        Duration between = Duration.between(begin, end);
        //获取毫秒值
        long time = between.toMinutes();
        //打印日志
        logger.info("当前请求"+request.getRequestURI()+"执行的时间为=" + time+"毫秒");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
